package com.hui.server.config.rabbit;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hui.server.entity.MailLog;
import com.hui.server.service.MailLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.server.config.rabbit
 * @Author: HUI
 * @CreateTime: 2022-04-16 09:41
 * @Description: 消息回调配置
 */

@Slf4j
@Component
public class RabbitCallbackConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback{


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MailLogService mailLogService;

    //rabbitTemplate 注入之后就设置该值
    @PostConstruct
    private void init() {
        rabbitTemplate.setConfirmCallback(this);
        /**
         * true：
         * 交换机无法将消息进行路由时，会将该消息返回给生产者
         * false：
         * 如果发现消息无法进行路由，则直接丢弃
         */
        rabbitTemplate.setMandatory(true);
        //设置回退消息交给谁处理
        rabbitTemplate.setReturnsCallback(this);
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String msgId = correlationData != null ? correlationData.getId() : "";
        if (ack) {
            log.info("交换机已经收到 id 为:{}的消息", msgId);
            mailLogService.update(new UpdateWrapper<MailLog>().set("status",1).eq("msgId",msgId));
        } else {
            log.info("交换机还未收到 id 为:{}消息,由于原因:{}", msgId, cause);
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {

        log.info("消息：{}，被服务器退回，原因是：{}，交换机是：{}，路由key：{}",
                returnedMessage.getMessage().toString(),
                returnedMessage.getReplyText(),
                returnedMessage.getExchange(),
                returnedMessage.getRoutingKey());
    }
}
